import React, {Fragment, PureComponent} from 'react';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {vehicleProperty, warrantyPolicyType, vehicleClaimType} from '../Enum';
import {Button, Spin, Divider, Collapse, Card, Row, Col, Table, Tabs} from 'antd';
import {PERMISSIONS} from './constants';
import {DATE_FORMAT, TABLE, DATETIME_FORMAT} from '../constants';
import routes from './routes';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {formatMessage} from './intl';
import {PermissionsContext} from './contexts';
import {formatNumber} from '../common/localize';
import {getWarrantyPolicyDetail, enableWarrantyPolicy, abandonWarrantyPolicy} from './api';
const {Description} = DescriptionList;
import {isHavePermission} from './utils';
const TabPane = Tabs.TabPane;
const Panel = Collapse.Panel;
const EMPTY_ARRAY = [];

export default class DetailPage extends PureComponent {
    state = {
        data: {},
        loading: false,
    };

    componentDidMount() {
        this.setState({
            loading: true
        });
        getWarrantyPolicyDetail(this.props.id).then(res => {
            if(res.ok)
                this.setState({
                    data: res.data,
                    loading: false
                });
            else
                this.setState({
                    loading: false
                });
        });
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
    }

    goBack = () => {
        this.props.history.push({
            pathname: routes.query.url(),
            state: {query: true}
        });
    }

    afterHandleOptions = () => {
        if(this.ismounted)
            this.setState({
                loading: false
            });
        this.goBack();
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        abandonWarrantyPolicy(this.props.id, {
            rowVersion: this.state.data.rowVersion
        }).then(this.afterHandleOptions);
    };

    handleEnableClick = () => {
        this.setState({
            loading: true
        });
        enableWarrantyPolicy(this.props.id, {
            rowVersion: this.state.data.rowVersion
        }).then(this.afterHandleOptions);
    };

    renderTabs = data => {
        const materialColumns = [
            {
                title: formatMessage({
                    id: 'detailPage.partWarrantyCategoryCode',
                    defaultMessage: '配件索赔分类编号'
                }),
                dataIndex: 'partWarrantyCategoryCode',
            },
            {
                title: formatMessage({
                    id: 'detailPage.partWarrantyCategoryName',
                    defaultMessage: '配件索赔分类名称'
                }),
                dataIndex: 'partWarrantyCategoryName',
            },
            {
                title: formatMessage({
                    id: 'detailPage.warrantyDuration',
                    defaultMessage: '索赔时间（月）'
                }),
                dataIndex: 'warrantyDuration',
            },
            {
                title: formatMessage({
                    id: 'detailPage.warrantyMileage',
                    defaultMessage: '索赔里程'
                }),
                dataIndex: 'warrantyMileage',
                render: text => formatNumber(text)
            },
            {
                title: formatMessage({
                    id: 'detailPage.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            },
        ];
            
        const tabs = data.map(item => {
            const {vehicles = EMPTY_ARRAY, id, warrantyPolicyType: type} = item;
            
            const vehiclePanel = vehicles.map(p => {
                const data = p.materials || EMPTY_ARRAY;
                const categoryHeader = <strong>{p.productCategoryCode}/{conventEnumValueToString(vehicleProperty, p.vehicleProperty)}/{conventEnumValueToString(vehicleClaimType, p.vehicleClaimType)}</strong>;
                const vinHeader = (<strong>{p.vin}</strong>);

                const vehicleHeader = type === warrantyPolicyType.标准 ? categoryHeader : vinHeader;

                return (
                    <Panel key={p.id} header={vehicleHeader}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="partId"
                            columns={materialColumns}
                            pagination={false}
                            dataSource={data}
                            {...TABLE} />
                    </Panel>
                );
            });
            return (
                <TabPane key={id} tab={conventEnumValueToString(warrantyPolicyType, type)}>
                    <Fragment>
                        <DescriptionList size="large" className={styles.marginBottom}>
                            <Description
                                term={formatMessage({id: 'detailPage.warrantyPolicyType',
                                    defaultMessage: '类型'})}>
                                {conventEnumValueToString(warrantyPolicyType, type)}
                            </Description>
                            <Description
                                term={formatMessage({id: 'detailPage.warrantyMileage',
                                    defaultMessage: '索赔里程'})}>
                                {formatNumber(item.warrantyMileage)}
                            </Description>
                            <Description
                                term={formatMessage({id: 'detailPage.warrantyMonth',
                                    defaultMessage: '索赔月份'})}>
                                {item.warrantyMonth}
                            </Description>
                            <Description
                                term={formatMessage({id: 'detailPage.saleStartDate',
                                    defaultMessage: '发车开始时间'})}>
                                {formatDateTime(item.saleStartDate, DATE_FORMAT)}
                            </Description>
                            <Description
                                term={formatMessage({id: 'detailPage.saleEndDate',
                                    defaultMessage: '发车结束时间'})}>
                                {formatDateTime(item.saleEndDate, DATE_FORMAT)}
                            </Description>
                        </DescriptionList>
                    </Fragment>
                    <Divider />
                    <Card title={formatMessage({
                        id: 'detailPage.detail.vehicles.title',
                        defaultMessage: '车辆车型清单'
                    })}>
                        <Collapse>
                            {vehiclePanel}
                        </Collapse>
                    </Card>
                </TabPane>
            );
        });
        return tabs;
    }
    renderOptions = () => {
        const {options = EMPTY_ARRAY} = this.state.data;
        return (
            <PermissionsContext.Consumer>
                {
                    pagePermissions =>
                        <Fragment>
                            {
                                isHavePermission(PERMISSIONS.update, pagePermissions, options) && (
                                    <Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">
                                        {formatMessage({
                                            id: 'detailPage.detail.btn.update',
                                            defaultMessage: '编辑'
                                        })}
                                    </Button>)
                            }
                            {
                                isHavePermission(PERMISSIONS.enable, pagePermissions, options) && (
                                    <WrappedPopconfirm
                                        id="enable"
                                        key="enable"
                                        title={formatMessage({
                                            id: 'detailPage.detail.popconfirm.message',
                                            defaultMessage: '是否继续?'
                                        })}
                                        okText={formatMessage({
                                            id: 'detailPage.detail.popconfirm.confirm',
                                            defaultMessage: '确认'
                                        })}
                                        cancelText={formatMessage({
                                            id: 'detailPage.detail.popconfirm.cancel',
                                            defaultMessage: '取消'
                                        })}
                                        onConfirm={this.handleEnableClick}>
                                        <Button size="small">
                                            {formatMessage({
                                                id: 'detailPage.detail.popconfirm.enable',
                                                defaultMessage: '生效'
                                            })}
                                        </Button>
                                    </WrappedPopconfirm>
                                )}
                            {
                                isHavePermission(PERMISSIONS.abandon, pagePermissions, options) && (
                                    <WrappedPopconfirm
                                        id="abandon"
                                        key="abandon"
                                        title={formatMessage({
                                            id: 'detailPage.detail.popconfirm.message',
                                            defaultMessage: '是否继续?'
                                        })}
                                        okText={formatMessage({
                                            id: 'detailPage.detail.popconfirm.confirm',
                                            defaultMessage: '确认'
                                        })}
                                        cancelText={formatMessage({
                                            id: 'detailPage.detail.popconfirm.cancel',
                                            defaultMessage: '取消'
                                        })}
                                        onConfirm={this.handleAbandonClick}>
                                        <Button size="small">
                                            {formatMessage({
                                                id: 'detailPage.detail.btn.abandon',
                                                defaultMessage: '作废'
                                            })}
                                        </Button>
                                    </WrappedPopconfirm>)
                            }
                        </Fragment>
                }
            </PermissionsContext.Consumer>
        );
    }
    render() {
        const data = this.state.data;
        const {items = EMPTY_ARRAY} = data;
        const tabs = this.renderTabs(items);
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Card>
                        <DescriptionList size="large" className={styles.marginBottom} title={<Row>
                            <Col span={6}>{formatMessage({
                                id: 'detailPage.detail.dealerInfo.title',
                                defaultMessage: '政策信息'
                            })}</Col>
                            <Col className={styles.optionBtn} span={18}>{this.renderOptions()}</Col>
                        </Row>}>
                            <Description
                                term={formatMessage({id: 'detailPage.detail.info.code',
                                    defaultMessage: '索赔政策编号'})}>
                                {data.code}
                            </Description>
                            <Description
                                term={formatMessage({id: 'detailPage.detail.info.name',
                                    defaultMessage: '索赔政策名称'})}>
                                {data.name}
                            </Description>
                            <Description
                                term={formatMessage({
                                    id: 'detailPage.detail.info.brandId',
                                    defaultMessage: '品牌'
                                })}>
                                {`(${data.brandCode})${data.brandName}`}
                            </Description>
                            <Description
                                term={formatMessage({
                                    id: 'detailPage.detail.info.dealerId',
                                    defaultMessage: '总代'
                                })}>
                                {`(${data.dealerCode})${data.dealerName}`}
                            </Description>
                            <Description
                                term={formatMessage({id: 'detailPage.detail.info.startTime',
                                    defaultMessage: '启用日期'})}>
                                {formatDateTime(data.startTime, DATETIME_FORMAT)}
                            </Description>
                        </DescriptionList>
                        <DescriptionList col={1} size="large">
                            <Description term={formatMessage({
                                id: 'detailPage.detail.info.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <Tabs>
                            {tabs}
                        </Tabs>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.props.loading} onClick={this.goBack}>
                        {formatMessage({
                            id: 'detailPage.detail.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
